package gwt.immunology.client.activity;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import gwt.immunology.client.ClientFactory;
import gwt.immunology.client.i18n.ImmunologyI18N;
import gwt.immunology.client.place.AddPatientPlace;
import gwt.immunology.client.place.AllPatientsPlace;
import gwt.immunology.client.service.PatientsService;
import gwt.immunology.client.service.PatientsServiceAsync;
import gwt.immunology.client.view.AddPatientView;
import gwt.immunology.shared.GenericDto;

public class AddPatientActivity extends AbstractActivity implements AddPatientView.Presenter {
    private ClientFactory clientFactory;
    private ImmunologyI18N i18n = GWT.create(ImmunologyI18N.class);
    private final PatientsServiceAsync patientsService = GWT.create(PatientsService.class);

    public AddPatientActivity(AddPatientPlace place, ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
        AddPatientView addPatientView = this.clientFactory.getAddPatientView();
        addPatientView.setPresenter(this);
        panel.setWidget(addPatientView.asWidget());
        Window.setTitle(i18n.registerNewPatient());
    }

    @Override
    public void registerNewPatient(GenericDto patient) {
        patientsService.registerNewPatient(patient, new AsyncCallback<GenericDto>() {

            @Override
            public void onFailure(Throwable caught) {
                Window.alert(i18n.patientRegistrationFailure());
            }

            @Override
            public void onSuccess(GenericDto result) {
                clientFactory.getPlaceController().goTo(new AllPatientsPlace());
            }
        });
    }

    @Override
    public void goTo(Place place) {
        this.clientFactory.getPlaceController().goTo(place);
    }

}
